package com.ljc.cjgl.service;


import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljc.cjgl.entitiy.Tea;
import com.ljc.cjgl.form.TeaForm;
import com.ljc.cjgl.repository.TeaRepository;
import com.ljc.cjgl.security.SysRole;
import com.ljc.cjgl.security.SysRoleRepository;

@Service
public class TeaService {
	@Autowired
	private TeaRepository teaDAO;
	@Autowired
	private SysRoleRepository sysRoleDAO;
	public Tea findById(Integer id) {
		Optional<Tea> optional = teaDAO.findById(id);
		if(optional.isPresent()) {
			return optional.get();
		}
		return null;
	}
	
	public List<Tea> findAll(){
		return teaDAO.findAll();
	}
	
	public Page<Tea> findAll(Specification<Tea> specification,Pageable pageable){
		return teaDAO.findAll(specification,pageable);
	}
	
	public Tea findByUsername(String username) {
		return teaDAO.findByUsername(username);
	}

	public synchronized boolean save(TeaForm form) {
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		Tea model=new Tea();
		Integer id = form.getId();
		if(id!=null) {
			model=findById(id);
		}else {
			model.setPassword(encoder.encode("123456"));
		}
		model.setName(form.getName());
		model.setUsername(form.getName());
		try {
			List<SysRole> roles=new ArrayList<SysRole>();
			for (String code : form.getRoles().split(",")) {
				SysRole role=sysRoleDAO.findByCode(code);
				roles.add(role);
			}
			model.setRoles(roles);
			teaDAO.save(model);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	public synchronized boolean delete(List<Tea> teas) {
		try {
			for (Tea tea : teas) {
				teaDAO.deleteById(tea.getId());
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public void save(Tea tea) {
		teaDAO.save(tea);
		
	}
}
